<template>
  <view class="page">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="card-content">
        <image class="avatar" :src="(userInfo && userInfo.avatar) || '/static/images/avatar-default.png'" mode="aspectFill" @click="goToLogin"></image>
        <view class="user-info" @click="goToLogin">
          <view class="nickname-row">
            <text class="nickname">{{ (userInfo && userInfo.nickname) || '点击登录' }}</text>
            <button class="edit-btn" v-if="isLoggedIn" @click.stop="goToEdit">编辑</button>
          </view>
          <text class="user-id" v-if="userInfo && userInfo.id">{{ userInfo.id }}</text>
        </view>
      </view>
      
      <!-- 快捷统计 -->
      <!-- <view class="stats-row">
        <view class="stat-item" @click="goToOrders(1)">
          <text class="stat-value">{{ stats.waitPay }}</text>
          <text class="stat-label">待支付</text>
        </view>
        <view class="stat-item" @click="goToOrders(2)">
          <text class="stat-value">{{ stats.waitAccept }}</text>
          <text class="stat-label">待接单</text>
        </view>
        <view class="stat-item" @click="goToOrders(3)">
          <text class="stat-value">{{ stats.delivering }}</text>
          <text class="stat-label">配送中</text>
        </view>
        <view class="stat-item" @click="goToOrders(4)">
          <text class="stat-value">{{ stats.finished }}</text>
          <text class="stat-label">已完成</text>
        </view>
      </view> -->
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <text class="section-title">常用功能</text>
      <view class="menu-list">
        <view class="menu-item" v-for="(menu, index) in menuList1" :key="index" @click="handleMenu(menu)">
          <view class="menu-icon" :style="{ background: menu.color }">
            <text class="menu-emoji">{{ menu.icon }}</text>
          </view>
          <text class="menu-name">{{ menu.name }}</text>
          <text class="menu-arrow">›</text>
        </view>
      </view>
    </view>

    <view class="menu-section" v-if="menuList2.length > 0">
      <text class="section-title">{{ sectionTitle2 }}</text>
      <view class="menu-list">
        <view class="menu-item" v-for="(menu, index) in menuList2" :key="index" @click="handleMenu(menu)">
          <view class="menu-icon" :style="{ background: menu.color }">
            <text class="menu-emoji">{{ menu.icon }}</text>
            <!-- 消息中心未读数角标 -->
            <view v-if="menu.name === '消息中心' && merchantUnreadCount > 0" class="badge">
              {{ merchantUnreadCount > 99 ? '99+' : merchantUnreadCount }}
            </view>
          </view>
          <text class="menu-name">{{ menu.name }}</text>
          <text class="menu-arrow">›</text>
        </view>
      </view>
    </view>

    <view class="menu-section">
      <text class="section-title">其他</text>
      <view class="menu-list">
        <view class="menu-item" v-for="(menu, index) in menuList3" :key="index" @click="handleMenu(menu)">
          <view class="menu-icon" :style="{ background: menu.color }">
            <text class="menu-emoji">{{ menu.icon }}</text>
          </view>
          <text class="menu-name">{{ menu.name }}</text>
          <text class="menu-arrow">›</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  data() {
    return {
      stats: {
        waitPay: 0,
        waitAccept: 0,
        delivering: 0,
        finished: 0
      },
      customerService: ''
    }
  },
  computed: {
    ...mapGetters('user', ['userType', 'userInfo', 'isLoggedIn']),
    
    // 根据用户类型显示不同的菜单
    menuList1() {
      const commonMenus = [
        { name: '收货地址', icon: '📍', color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', path: '/pages/address/list' },
        { name: '我的反馈', icon: '💬', color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)', path: '/pages/feedback/list' }
      ]
      
      // 普通用户额外菜单
      if (this.userType === 1) {
        return [
          ...commonMenus
          // { name: '优惠券', icon: '🎫', color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)', path: '' },
          // { name: '我的积分', icon: '⭐', color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', path: '' }
        ]
      }
      
      return commonMenus
    },
    
    menuList2() {
      // 普通用户：显示代取服务相关入口
      if (this.userType === 1) {
        return [
          { name: '我的发布', icon: '📝', color: 'linear-gradient(135deg, #4ECDC4, #44A08D)', path: '/pages/pickup/my-publish' },
          { name: '我的接单', icon: '🤝', color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', path: '/pages/pickup/my-orders' },
          { name: '任务大厅', icon: '🎯', color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)', path: '/pages/pickup/available' },
          { name: '收益统计', icon: '💰', color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', path: '/pages/settlement/statistics' }
        ]
      }
      
      // 商家：商品、订单、配送、结算管理（商家自己配送零食，管理代取结算）
      if (this.userType === 3) {
        return [
          { name: '消息中心', icon: '🔔', color: 'linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%)', path: '/pages/merchant/message' },
          { name: '商品管理', icon: '📦', color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)', path: '/pages/merchant/products' },
          { name: '订单管理', icon: '📝', color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)', path: '/pages/merchant/orders' },
          { name: '反馈管理', icon: '💬', color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)', path: '/pages/merchant/feedback-list' },
          { name: '退款管理', icon: '💸', color: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)', path: '/pages/merchant/refund-list' },
          { name: '待配送订单', icon: '🚚', color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', path: '/pages/merchant/delivery' },
          { name: '结算管理', icon: '💰', color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', path: '/pages/merchant/settlement' },
          { name: '数据统计', icon: '📊', color: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)', path: '/pages/merchant/stats' },
          { name: '系统配置', icon: '⚙️', color: 'linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%)', path: '/pages/merchant/settings' }
        ]
      }
      
      return []
    },
    
    menuList3() {
      return [
        { name: '客服中心', icon: '👨‍💼', color: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)', path: '' },
        // { name: '关于我们', icon: 'ℹ️', color: 'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)', path: '' },
        // { name: '设置', icon: '⚙️', color: 'linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%)', path: '/pages/user/settings' },
        { name: '退出登录', icon: '🚪', color: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)', action: 'logout' }
      ]
    },
    
    // 根据用户类型显示不同的标题
    sectionTitle2() {
      if (this.userType === 3) return '商家管理'
      if (this.userType === 1) return '代取服务'
      return '我的服务'
    },
    
    // 商家未读数（从全局store获取）
    merchantUnreadCount() {
      return Number(this.$store.state.merchantUnreadCount) || 0
    }
  },
  onLoad() {
    // 首次加载，如果store中没有用户信息则请求
    this.loadUserInfo()
    this.loadStats()
  },
  onShow() {
    // 只刷新统计数据，用户信息使用store缓存
    this.loadStats()
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    async loadCustomerService() {
      try {
        const { getConfig } = require('@/api/config')
        const cs = await getConfig('customer_service')
        this.customerService = (cs || '').toString()
      } catch (_) {
        this.customerService = ''
      }
    },
    
    /**
     * 加载用户信息
     * @param {Boolean} forceRefresh - 是否强制刷新（忽略缓存）
     */
    async loadUserInfo(forceRefresh = false) {
      const token = uni.getStorageSync('ss_satoken')
      if (!token) {
        return
      }
      
      // 如果store中已有用户信息且不是强制刷新，则直接使用缓存
      if (!forceRefresh && this.userInfo && this.userInfo.id) {
        return
      }
      
      try {
        // 调用Vuex action获取用户信息
        await this.getUserInfo()
      } catch (error) {
        // 如果token失效，清除本地存储
        if (error.code === 401) {
          this.$store.dispatch('user/logout')
        }
      }
    },
    async loadStats() {
      const token = uni.getStorageSync('ss_satoken')
      if (!token) {
        this.stats = {
          waitPay: 0,
          waitAccept: 0,
          delivering: 0,
          finished: 0
        }
        return
      }
      
      try {
        // TODO: 后续可以添加统计API
        // 暂时使用模拟数据
        this.stats = {
          waitPay: 0,
          waitAccept: 0,
          delivering: 0,
          finished: 0
        }
      } catch (error) {
        // 关闭日志
      }
    },
    goToLogin() {
      if (!this.isLoggedIn) {
        uni.navigateTo({
          url: '/pages/user/login'
        })
      }
    },
    goToEdit() {
      if (!this.isLoggedIn) {
        uni.navigateTo({ url: '/pages/user/login' })
        return
      }
      uni.navigateTo({ url: '/pages/user/edit' })
    },
    goToOrders(tab) {
      uni.switchTab({
        url: '/pages/order/index'
      })
      // TODO: 切换到对应tab
    },
    handleMenu(menu) {
      // 客服中心：无需登录，点击时才加载配置
      if (menu.name === '客服中心') {
        this.loadCustomerService().then(() => {
          if (!this.customerService) {
            uni.showToast({ title: '暂未配置客服联系方式', icon: 'none' })
          } else {
            uni.showModal({
              title: '客服联系方式',
              content: this.customerService,
              showCancel: false
            })
          }
        })
        return
      }
      // 检查是否登录
      if (!this.isLoggedIn && menu.action !== 'logout') {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/user/login' })
        }, 1500)
        return
      }
      
      // 处理特殊动作
      if (menu.action === 'logout') {
        if (!this.isLoggedIn) {
          uni.showToast({
            title: '您还未登录',
            icon: 'none'
          })
          return
        }
        
        uni.showModal({
          title: '提示',
          content: '确定要退出登录吗？',
          success: (res) => {
            if (res.confirm) {
              // 调用Vuex logout action
              this.$store.dispatch('user/logout')
              
              // 清除统计数据
              this.stats = {
                waitPay: 0,
                waitAccept: 0,
                delivering: 0,
                finished: 0
              }
              
              uni.showToast({
                title: '已退出登录',
                icon: 'success'
              })
              
              // 跳转到登录页
              setTimeout(() => {
                uni.navigateTo({
                  url: '/pages/user/login'
                })
              }, 1500)
            }
          }
        })
        return
      }
      
      
      // 需要登录的功能
      const needLoginPaths = [
        '/pages/address/list', 
        '/pages/feedback/list',
        '/pages/pickup/my-publish',
        '/pages/pickup/my-orders',
        '/pages/pickup/available',
        '/pages/settlement/statistics'
      ]
      if (needLoginPaths.includes(menu.path) && !this.isLoggedIn) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/user/login'
              })
            }
          }
        })
        return
      }
      
      // 正常跳转
      if (menu.path) {
        uni.navigateTo({
          url: menu.path
        })
      } else {
        uni.showToast({
          title: '功能开发中...',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 40rpx;
}

/* 用户信息卡片 */
.user-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 32rpx 24rpx;
  margin-bottom: 24rpx;
  border-radius: 20rpx;
  margin: 16rpx 20rpx 24rpx;
}

.card-content {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(255, 255, 255, 0.4);
  flex-shrink: 0;
  background: rgba(255, 255, 255, 0.1);
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  justify-content: center;
}

.nickname-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex-wrap: wrap;
}

.nickname {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
}

.user-id {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.85);
  word-break: break-all;
}

.stats-row {
  display: flex;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 16rpx;
  padding: 24rpx 0;
  backdrop-filter: blur(10px);
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  
  &:not(:last-child) {
    border-right: 1rpx solid rgba(255, 255, 255, 0.2);
  }
  
  .stat-value {
    font-size: 40rpx;
    font-weight: bold;
    color: #fff;
  }
  
  .stat-label {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.9);
  }
}

/* 功能菜单 */
.menu-section {
  margin-bottom: 20rpx;
  
  .section-title {
    display: block;
    padding: 24rpx 20rpx 16rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.menu-list {
  background: #fff;
  border-radius: 16rpx;
  margin: 0 20rpx;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 28rpx 24rpx;
  gap: 20rpx;
  
  &:not(:last-child) {
    border-bottom: 1rpx solid #f5f5f5;
  }
  
  &:active {
    background: #f8f8f8;
  }
}

.menu-icon {
  width: 72rpx;
  height: 72rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  .menu-emoji {
    font-size: 36rpx;
  }
  
  .badge {
    position: absolute;
    top: -8rpx;
    right: -8rpx;
    background: #ff4d4f;
    color: #fff;
    border-radius: 50%;
    min-width: 32rpx;
    height: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20rpx;
    font-weight: bold;
    border: 2rpx solid #fff;
  }
}

.menu-name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.menu-arrow {
  font-size: 48rpx;
  color: #ccc;
  font-weight: 300;
}

.edit-btn {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  background: rgba(255, 255, 255, 0.35);
  color: #fff;
  font-size: 22rpx;
  border: none;
  white-space: nowrap;
  flex-shrink: 0;
  font-weight: 500;
}
</style>

